package cn.calm.swing.osgi.mysql.blance.ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;

import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.beansbinding.Bindings;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.beansbinding.Property;
import org.jdesktop.observablecollections.ObservableCollections;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import cn.calm.swing.osgi.api.ProjectPersistenceService;
import cn.calm.swing.osgi.api.ProjectService;
import cn.calm.swing.osgi.api.entity.Project;
import cn.calm.swing.osgi.api.exception.SwingException;
import cn.calm.swing.osgi.api.util.EntityUtil;
import cn.calm.swing.osgi.mysql.blance.entity.HostInfo;
import cn.calm.swing.osgi.mysql.blance.entity.MasterInfo;
import cn.calm.swing.osgi.mysql.blance.service.MySqlBlanceProjectService;
import cn.calm.swing.osgi.util.SwingHelper;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MySqlBlanceProjectDialog extends JDialog{
	/**
	 * 
	 */
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	private static final long serialVersionUID = 1L;
	public static  final String MYSQL_PROJECT_TYPE="swing.osgi.mysql.blance";
	
	private JTextField port;
	private JButton run;
	private JTextField slavePassword;
	private JTextField slaveUsername;
	private JTextField slavePort;
	private JTextField slaveHostname;
	private JPasswordField password;
	private JTextField username;
	private JTextField masterHostName;
	private JTable slaveInfoTable;
	private JTextField projectName;
	private JButton subSlave;
	
	private Project project ;
	private List<HostInfo> slaveHosts;
	private HostInfo masterHost;
	private ProjectPersistenceService persistenceService;
	public MySqlBlanceProjectDialog(final BundleContext context) {
		JLabel slavePasswordLb;
		JLabel slaveUsernameLb;
		JLabel slavePortLb;
		JLabel slaveHostLb;
		JPanel slavePanel;
		JButton ok;
		JButton addSlave;
		JPanel slaveOptionPan;
		JScrollPane slaveHostPanel;
		JLabel slaveHost;
		JPanel contentPanel;
		JButton cancel;
		JPanel buttonPan;
		JLabel projectNameLb;
		JLabel usernameLb;
		JLabel passwordLb;
		JLabel portLb;
		JLabel masterHostLb;
		this.setSize(531, 407);
		BorderLayout thisLayout = new BorderLayout();
		setModal(true);
		getContentPane().setLayout(thisLayout);
		{
			buttonPan = new JPanel();
			FlowLayout buttonPanLayout = new FlowLayout();
			buttonPanLayout.setAlignment(FlowLayout.RIGHT);
			getContentPane().add(buttonPan, BorderLayout.SOUTH);
			buttonPan.setLayout(buttonPanLayout);
			{
				run = new JButton();
				buttonPan.add(run);
				run.setText("\u8fd0\u884c");
				run.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						try {
							validateData();
							run();
						} catch (Exception e) {
							JOptionPane.showMessageDialog(MySqlBlanceProjectDialog.this, e.getMessage());
						}
					}
				});
			}
			{
				ok = new JButton();
				buttonPan.add(ok);
				ok.setText("\u4fdd\u5b58");
				ok.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						try {
							validateData();
							project.setType(MYSQL_PROJECT_TYPE);
							ServiceReference<ProjectPersistenceService> serviceReference = context.getServiceReference(ProjectPersistenceService.class);
							persistenceService=context.getService(serviceReference);
							project.getProperties().clear();
							EntityUtil.entityToMap(project,masterHost, "masterHost");
							for(int i=0;i<slaveHosts.size();i++){
								EntityUtil.entityToMap(project,slaveHosts.get(i), "slaveHosts["+i+"]");
							}
							Hashtable<String, Object> dir=new Hashtable<String, Object>();
							dir.put(ProjectService.PROJECT_TYPE, MYSQL_PROJECT_TYPE);
							if(project.getId()==null){
								persistenceService.add(project);
							}else{
								persistenceService.update(project);
								ProjectService.projectServiceRegistration.get(project.getId()).unregister();
							}
							dir.put(ProjectService.PROJECT_ID, project.getId());
							MySqlBlanceProjectService service=new MySqlBlanceProjectService(context);
							service.setProject(project);
							ServiceRegistration<ProjectService> registerService = context.registerService(ProjectService.class, service, dir);
							ProjectService.projectServiceRegistration.put(project.getId(), registerService);
							MySqlBlanceProjectDialog.this.dispose();
							context.ungetService(serviceReference);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(MySqlBlanceProjectDialog.this, e.getMessage());
						}
					}
				});
				cancel = new JButton();
				buttonPan.add(cancel);
				cancel.setText("\u53d6\u6d88");
				cancel.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						dispose();
					}
				});
			}
		}
		{
			contentPanel = new JPanel();
			GridBagLayout contentPanelLayout = new GridBagLayout();
			contentPanelLayout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
			contentPanelLayout.rowHeights = new int[] {30, 30, 30, 195};
			contentPanelLayout.columnWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0};
			contentPanelLayout.columnWidths = new int[] {90, 150, 90, 150, 30};
			getContentPane().add(contentPanel, BorderLayout.CENTER);
			contentPanel.setLayout(contentPanelLayout);
			contentPanel.setPreferredSize(new java.awt.Dimension(534, 341));
			{
				projectNameLb = new JLabel();
				contentPanel.add(projectNameLb, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
				projectNameLb.setText("\u9879\u76ee\u540d:");
			}
			{
				projectName = new JTextField();
				contentPanel.add(projectName, new GridBagConstraints(1, 0, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				projectName.setPreferredSize(new java.awt.Dimension(280, 22));
			}
			{
				masterHostLb = new JLabel();
				contentPanel.add(masterHostLb, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
				masterHostLb.setText("\u4e3b\u670d\u52a1\u5668\u540d:");
			}
			{
				masterHostName = new JTextField();
				contentPanel.add(masterHostName, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				masterHostName.setPreferredSize(new java.awt.Dimension(280, 22));
			}
			{
				portLb = new JLabel();
				contentPanel.add(portLb, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
				portLb.setText("\u7aef\u53e3:");
			}
			{
				usernameLb = new JLabel();
				contentPanel.add(usernameLb, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
				usernameLb.setText("\u7528\u6237\u540d:");
			}
			{
				passwordLb = new JLabel();
				contentPanel.add(passwordLb, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
				passwordLb.setText("\u5bc6\u7801:");
			}
			{
				port = new JTextField();
				contentPanel.add(port, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				port.setText("3306");
				port.setPreferredSize(new java.awt.Dimension(280, 22));
			}
			{
				username = new JTextField();
				contentPanel.add(username, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				username.setPreferredSize(new java.awt.Dimension(280, 22));
			}
			{
				password = new JPasswordField();
				contentPanel.add(password, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				password.setPreferredSize(new java.awt.Dimension(271, 22));
			}
			{
				slaveHost = new JLabel();
				contentPanel.add(slaveHost, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(10, 0, 0, 10), 0, 0));
				slaveHost.setText("\u4ece\u670d\u52a1\u5668:");
			}
			{
				slaveHostPanel = new JScrollPane();
				contentPanel.add(slaveHostPanel, new GridBagConstraints(1, 3, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
				{
					slaveInfoTable = new JTable();
					slaveInfoTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
					slaveHostPanel.setViewportView(slaveInfoTable);
				}
				slaveHostPanel.setFocusCycleRoot(true);
			}
			{
				slaveOptionPan = new JPanel();
				GridBagLayout slaveOptionPanLayout = new GridBagLayout();
				slaveOptionPanLayout.rowWeights = new double[] {0.0, 0.0, 0.1};
				slaveOptionPanLayout.rowHeights = new int[] {40, 40, 7};
				slaveOptionPanLayout.columnWeights = new double[] {0.1};
				slaveOptionPanLayout.columnWidths = new int[] {7};
				slaveOptionPan.setLayout(slaveOptionPanLayout);
				contentPanel.add(slaveOptionPan, new GridBagConstraints(4, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 2, 0, 0), 0, 0));
				{
					addSlave = new JButton();
					slaveOptionPan.add(addSlave, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
					addSlave.setText("+");
					addSlave.setMargin(new java.awt.Insets(0, 0, 0, 0));
					addSlave.setPreferredSize(new java.awt.Dimension(30, 30));
					addSlave.setMaximumSize(new java.awt.Dimension(30, 30));
					addSlave.setMinimumSize(new java.awt.Dimension(30, 30));
					addSlave.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							slaveHosts.add(new HostInfo());
							slaveInfoTable.repaint();
						}
					});
					subSlave = new JButton();
					slaveOptionPan.add(subSlave, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
					subSlave.setText("-");
					subSlave.setMaximumSize(new java.awt.Dimension(30, 30));
					subSlave.setMargin(new java.awt.Insets(0, 0, 0, 4));
					subSlave.setMinimumSize(new java.awt.Dimension(30, 30));
					subSlave.setPreferredSize(new java.awt.Dimension(30, 30));
					subSlave.setEnabled(false);
					subSlave.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							slaveHosts.remove(slaveInfoTable.getSelectedRow());
							slaveInfoTable.repaint();
						}
					});
				}
				slavePanel = new JPanel();
				GridBagLayout slavePanelLayout = new GridBagLayout();
				contentPanel.add(slavePanel, new GridBagConstraints(1, 4, 3, 2, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
				slavePanel.setPreferredSize(new java.awt.Dimension(390, 38));
				slavePanelLayout.rowWeights = new double[] {0.0, 0.0};
				slavePanelLayout.rowHeights = new int[] {25, 25};
				slavePanelLayout.columnWeights = new double[] {0.0, 0.1, 0.0, 0.1};
				slavePanelLayout.columnWidths = new int[] {50, 7, 50, 7};
				slavePanel.setLayout(slavePanelLayout);
				{
					slaveHostLb = new JLabel();
					slavePanel.add(slaveHostLb, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
					slaveHostLb.setText("\u4e3b\u673a\u540d:");
				}
				{
					slaveHostname = new JTextField();
					slavePanel.add(slaveHostname, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				}
				{
					slavePortLb = new JLabel();
					slavePanel.add(slavePortLb, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
					slavePortLb.setText("\u7aef\u53e3:");
				}
				{
					slavePort = new JTextField();
					slavePanel.add(slavePort, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				}
				{
					slaveUsernameLb = new JLabel();
					slavePanel.add(slaveUsernameLb, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
					slaveUsernameLb.setText("\u7528\u6237\u540d:");
				}
				{
					slaveUsername = new JTextField();
					slavePanel.add(slaveUsername, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				}
				{
					slavePasswordLb = new JLabel();
					slavePanel.add(slavePasswordLb, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
					slavePasswordLb.setText("\u5bc6\u7801:");
				}
				{
					slavePassword = new JPasswordField();
					slavePanel.add(slavePassword, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
				}
			}
		}

		BeanProperty<JTable, String> tableBeanProperty = BeanProperty.create("selectedElement.hostName");
		BeanProperty<JTextField, String> textFieldBeanProperty = BeanProperty.create("text");
		AutoBinding<JTable, String, JTextField, String> autoBinding = Bindings.createAutoBinding(AutoBinding.UpdateStrategy.READ_WRITE, slaveInfoTable, tableBeanProperty, slaveHostname, textFieldBeanProperty);
		autoBinding.bind();
		
		tableBeanProperty = BeanProperty.create("selectedElement.port");
		autoBinding = Bindings.createAutoBinding(AutoBinding.UpdateStrategy.READ_WRITE, slaveInfoTable, tableBeanProperty, slavePort, textFieldBeanProperty);
		autoBinding.bind();
		
		tableBeanProperty = BeanProperty.create("selectedElement.username");
		autoBinding = Bindings.createAutoBinding(AutoBinding.UpdateStrategy.READ_WRITE, slaveInfoTable, tableBeanProperty, slaveUsername, textFieldBeanProperty);
		autoBinding.bind();
		
		tableBeanProperty = BeanProperty.create("selectedElement.password");
		autoBinding = Bindings.createAutoBinding(AutoBinding.UpdateStrategy.READ_WRITE, slaveInfoTable, tableBeanProperty, slavePassword, textFieldBeanProperty);
		autoBinding.bind();
		
		ELProperty<JTable, Object> jTableEvalutionProperty = ELProperty.create("${ selectedElement != null }");
		BeanProperty<JButton, Boolean> jButtonBeanProperty_2 = BeanProperty.create("enabled");
		AutoBinding<JTable, Object, JButton, Boolean> autoBinding_7 = Bindings.createAutoBinding(AutoBinding.UpdateStrategy.READ, slaveInfoTable, jTableEvalutionProperty, subSlave, jButtonBeanProperty_2);
		autoBinding_7.bind();
		SwingHelper.center(this);
//		initDatabinding();
	}
	
	private void run() throws SwingException {
		// TODO
		Connection slaveCon;
		Connection masterCon = null ;
		MasterInfo info = null;
		masterCon = getHostConnection(masterHost);
		Statement masterStatement;
		try {
			masterStatement = masterCon.createStatement();
			for (HostInfo hi : slaveHosts) {
				slaveCon = getHostConnection(hi);
				
				ResultSet rs = masterStatement.executeQuery("show master status");
				if(rs.next()){
					info =new MasterInfo(rs.getString("file"), rs.getString("position"));
				}else{
					throw new SwingException("对不起,"+masterHost+"没有开启log-bin!\n请在my.ini文件中添加:\nlog-bin=mysql-bin\nserver-id=数字");
				}
				try {
					Statement slaveStatement = slaveCon.createStatement();
					String sql="stop slave";
					slaveStatement.addBatch(sql);
					sql = String
							.format("change master to MASTER_HOST='%s', MASTER_PORT=%d, MASTER_USER='%s',MASTER_PASSWORD='%s', MASTER_LOG_FILE='%s',MASTER_LOG_POS=%s",
									masterHost.getHostName(), masterHost.getPort(),
									masterHost.getUsername(),
									masterHost.getPassword(), info.getFile(),
									info.getPosition());
					slaveStatement.addBatch(sql);
					slaveStatement.executeBatch();
					sql="start slave";
					slaveStatement.clearBatch();
					slaveStatement.addBatch(sql);
					slaveStatement.executeBatch();
				} catch (SQLException e) {
					throw new SwingException(hi+"\n"+e.getMessage());
				} finally{
					if (slaveCon != null) {
						try {
							slaveCon.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}finally{
			if (masterCon != null) {
				try {
					masterCon.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private Connection getHostConnection(HostInfo hi) throws SwingException{
		Connection con = null;
		try {
			con=DriverManager.getConnection(String.format("jdbc:mysql://%s:%d/mysql", hi.getHostName(),hi.getPort()), hi.getUsername(), hi.getPassword());
		} catch (SQLException e) {
			if(e.getErrorCode()==1045){
				throw new SwingException("对不起，"+hi+"用户名或密码错误!");
			}
		}
		return con;
	}
	
	public void closeConnection(Connection con){
		if(con!=null){
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void initDatabinding() {
		slaveHostname.setText("");
		slavePort.setText("");
		slavePassword.setText("");
		slaveUsername.setText("");
		//项目名绑定
		BeanProperty<JTextField, String> field = BeanProperty.create("text");
		BeanProperty<Project, String> property = BeanProperty.create("name");
		AutoBinding<Project, String, JTextField, String> binding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, project, property, projectName,field);
		binding.bind();
		
		//主服务器主机名绑定
		BeanProperty<HostInfo, String> masterHostProperty = BeanProperty.create("hostName");
		AutoBinding<HostInfo, String, JTextField, String> masterHostBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, masterHost, masterHostProperty, masterHostName,field);
		masterHostBinding.bind();
		
		//主服务器端口绑定
		masterHostProperty = BeanProperty.create("port");
		masterHostBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, masterHost, masterHostProperty, port,field);
		masterHostBinding.bind();
		
		//主服务器用户名绑定
		masterHostProperty = BeanProperty.create("username");
		masterHostBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, masterHost, masterHostProperty, username,field);
		masterHostBinding.bind();
		
		//主服务器密码绑定
		masterHostProperty = BeanProperty.create("password");
		masterHostBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, masterHost, masterHostProperty, password,field);
		masterHostBinding.bind();
		//从服务器信息绑定
		BeanProperty<MySqlBlanceProjectDialog, List<HostInfo>> slaveHosts = BeanProperty.create("slaveHosts");
		JTableBinding<HostInfo, MySqlBlanceProjectDialog, JTable> tableBinding = SwingBindings.createJTableBinding(UpdateStrategy.READ, this,slaveHosts,  slaveInfoTable);
		Property<HostInfo, String> columnProperty= BeanProperty.create("hostName");
		tableBinding.addColumnBinding(columnProperty).setColumnName("主机名").setEditable(false);
		
		columnProperty= BeanProperty.create("port");
		tableBinding.addColumnBinding(columnProperty).setColumnName("端口").setEditable(false);
		
		tableBinding.bind();
	}

	public Project getProject() {
		return project;
	}

	public void setProject(Project project) {
		this.project = project;
	}

	public List<HostInfo> getSlaveHosts() {
		return slaveHosts;
	}

	public void setSlaveHosts(List<HostInfo> slaveHosts) {
		slaveHosts=ObservableCollections.observableList(slaveHosts);
		this.slaveHosts = slaveHosts;
	}
	
	public void setMasterHost(HostInfo masterHost) {
		this.masterHost = masterHost;
	}
	
	public HostInfo getMasterHost() {
		return masterHost;
	}
	
	public void validateData() throws SwingException {
		EntityUtil.validate(project);
		EntityUtil.validate(masterHost);
		for (HostInfo hi : slaveHosts) {
			EntityUtil.validate(hi);
		}
		Set<HostInfo> set = new HashSet<HostInfo>();
		validateDuplicateHost(set, masterHost);
		for (HostInfo hi : slaveHosts) {
			validateDuplicateHost(set, hi);
		}
		
		validateHostPot(masterHost);

		for (HostInfo hi : slaveHosts) {
			validateHostPot(hi);
		}
	}

	private void validateDuplicateHost(Set<HostInfo> set, HostInfo hi)
			throws SwingException {
		if (set.contains(hi)) {
			throw new SwingException("对不起，" + hi + "已经存在!");
		} else {
			set.add(hi);
		}
	}

	private void validateHostPot(HostInfo hi) throws SwingException {
		Socket client = null;
		try {
			client = new Socket(hi.getHostName(), hi.getPort());
			client.close();
		} catch (Exception e) {
			throw new SwingException("对不起，" + hi + "不可到达!");
		}
	}
	
	@Override
	public void setVisible(boolean b) {
		if(b){
			initDatabinding();
		}
		super.setVisible(b);
	}
}
